import jwt from 'jsonwebtoken';
import Router from 'koa-router';
import { users } from '../db/models.js';

const login = new Router();
const secret = 'duckDuckers';

login.post('/', async (ctx) => {
    const { id, passwd } = ctx.request.body;
    let result = await users.findOne({ id: id, passwd: passwd });
    if (!!result) {
        // If authentication is successful, issue a JWT token
        const payload = {
            id: id,
            role: result.role,
        };
        const token = jwt.sign(payload, secret, { expiresIn: '7d' }); // Token expires in 7 days
        ctx.body = {
            code: 200,
            message: '登录成功',
            data: {
                token: token,
            },
        };
    } else {
        ctx.body = {
            code: 401,
            message: '用户名或密码错误',
        };
    }
});

export default login;
